package com.smedi.ismedi.file.core.infrastructure.FileConvert;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * openOffice工具类
 *
 * @author jiangqinxuan
 * @date 2021/08/19
 */
public class OpenOfficeUtil {
    public static byte[] convertToPdf(MultipartFile inputMultipartFile) throws IOException {
        //inputMultipartFile转为inputFile
        // 获取文件名
        String fileName = inputMultipartFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 用uuid作为文件名，防止生成的临时文件重复
        final File inputFile = File.createTempFile(UUID.randomUUID().toString(), prefix);
        // MultipartFile to File
        inputMultipartFile.transferTo(inputFile);

        // 转换execl为pdf
        final File outputFile = File.createTempFile(UUID.randomUUID().toString(), ".pdf");
        OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
        DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
        converter.convert(inputFile, outputFile);

        // outputFile转换为字节流输出出去
        Path path = Paths.get(outputFile.getAbsolutePath());
        return Files.readAllBytes(path);
    }

    private OpenOfficeUtil() {
        throw new IllegalStateException("Utility class");
    }
}
